<template>
  <div class="main_spac1 maincl">
    <div class="main_white padding10">
      <div class="mainor_form">
        <el-form
          :inline="true"
          :model="searchForm"
          class="demo-form-inline"
          ref="searchForm"
          label-width="70px"
          id="form"
        >
          <el-form-item label="品名：" prop="goods_name">
            <el-input
              class="wid220"
              placeholder="请输入品名"
              v-model="searchForm.goods_name"
            ></el-input>
          </el-form-item>
          <MainFormBtn @reset="reset" @getSearchFor="getData" :loading="loading" :showBtn="false">
          </MainFormBtn>
          <div class="clearfix"></div>
        </el-form>
        <div class="main-controls-wrap">
          <div>
            <el-button
              type="primary"
              @click="
                dialogVisible = true;
                title = '收票';
              "
              >收票</el-button
            >
            <el-button
              type="primary"
              @click="
                dialogVisible = true;
                title = '出票';
              "
              >出票</el-button
            >
            <el-button type="primary" @click="tohistory">历史单据</el-button>
          </div>
        </div>
      </div>
      <div class="main_table" style="min-height: 590px">
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
        >
          <el-table-column align="center" label="品名" prop="goods_name" />
          <el-table-column align="center" label="数量" prop="num" />
          <el-table-column
            align="center"
            label="操作"
            fixed="right"
            width="250"
          >
            <template slot-scope="scope">
              <el-link type="success" @click="handleGenerate(scope.row)"
                >出票</el-link
              >
              <router-link :to="'/financial/watchBill/' + scope.row.goods_name">
                <el-link type="success">记录</el-link>
              </router-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="main_page boxdq">
        <div></div>
        <!-- 分页 -->
        <div class="main_page_r">
          <MainPagination
            :current-page="current"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background
            @size-change="changeSize"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
    <!-- 收票 出票 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      @close="handleClose"
      class="main_dialog"
    >
      <div class="main_tile_l">
        <em></em>
        基础信息
      </div>
      <el-form
        :model="tableForm"
        status-icon
        :rules="rules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="addForm_flex">
          <el-form-item
            label="发票日期："
            :rules="rules.invoice_time"
            prop="addForm.invoice_time"
          >
            <el-date-picker
              class="wid220"
              v-model="tableForm.addForm.invoice_time"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="发票号码："
            :rules="rules.invoice_code"
            prop="addForm.invoice_code"
          >
            <el-input
              class="wid220"
              v-model="tableForm.addForm.invoice_code"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="开票单位："
            :rules="rules.invoice_entity"
            prop="addForm.invoice_entity"
          >
            <el-input
              class="wid220"
              v-model="tableForm.addForm.invoice_entity"
            ></el-input>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input
              class="wid220"
              v-model="tableForm.addForm.remark"
            ></el-input>
          </el-form-item>
        </div>

        <div class="main_tile_l">
          <em></em>
          商品信息
        </div>
        <div class="main_table table_scroll table_guanli">
          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableForm.addForm_goods"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            :cell-style="{
              height: '70px',
            }"
          >
            <el-table-column
              v-if="title == '出票'"
              align="center"
              label="品名"
              prop="goods_name"
            >
              <template slot-scope="scope">
                <el-form-item
                  label=""
                  :prop="'addForm_goods.' + scope.$index + '.goods_name'"
                  :rules="
                    tableForm.addForm_goods.length - 1 !== scope.$index
                      ? rules.goods_name
                      : []
                  "
                >
                  <el-autocomplete
                    v-model="scope.row.goods_name"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="品名"
                    @select="
                      (item) => {
                        handleSelect(item, scope.$index);
                      }
                    "
                  ></el-autocomplete>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="title == '收票'" align="center" label="品名">
              <template slot-scope="scope">
                <el-form-item
                  label=""
                  :prop="'addForm_goods.' + scope.$index + '.goods_name'"
                  :rules="
                    tableForm.addForm_goods.length - 1 !== scope.$index
                      ? rules.goods_name
                      : []
                  "
                >
                  <el-input
                    placeholder="品名"
                    v-model="scope.row.goods_name"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="title == '收票'" align="center" label="数量">
              <template slot-scope="scope">
                <el-form-item
                  label=""
                  :prop="'addForm_goods.' + scope.$index + '.num'"
                  :rules="
                    tableForm.addForm_goods.length - 1 !== scope.$index
                      ? rules.num
                      : []
                  "
                >
                  <el-input
                    placeholder="数量"
                    v-model="scope.row.num"
                    oninput="value=value.replace(/[^0-9.]/g,'')"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              v-if="title == '出票'"
              align="center"
              label="剩余数量"
              prop="sy_num"
            >
              <template slot-scope="scope">
                <el-input
                  placeholder="剩余数量"
                  v-model="scope.row.sy_num"
                  disabled
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              v-if="title == '出票'"
              align="center"
              label="出票数量"
              prop="num"
            >
              <template slot-scope="scope">
                <el-form-item
                  label=""
                  :prop="'addForm_goods.' + scope.$index + '.sy_num'"
                  :rules="
                    tableForm.addForm_goods.length - 1 !== scope.$index
                      ? rules.sy_num
                      : []
                  "
                >
                  <el-input
                    placeholder="出票数量"
                    v-model="scope.row.num"
                    oninput="value=value.replace(/[^0-9.]/g,'')"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单价" prop="unit">
              <template slot-scope="scope">
                <el-form-item
                  label=""
                  :prop="'addForm_goods.' + scope.$index + '.unit'"
                  :rules="
                    tableForm.addForm_goods.length - 1 !== scope.$index
                      ? rules.unit
                      : []
                  "
                >
                  <el-input
                    placeholder="单价"
                    v-model="scope.row.unit"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="金额" prop="money">
              <template slot-scope="scope">
                <el-form-item
                  label=""
                  :prop="'addForm_goods.' + scope.$index + '.money'"
                  :rules="
                    tableForm.addForm_goods.length - 1 !== scope.$index
                      ? rules.money
                      : []
                  "
                >
                  <el-input
                    placeholder="金额"
                    v-model="scope.row.money"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="备注" prop="remark">
              <template slot-scope="scope">
                <el-input
                  placeholder="备注"
                  v-model="scope.row.remark"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" fixed="right">
              <template v-slot="scope">
                <el-link
                  v-if="scope.row.delete"
                  type="danger"
                  @click="handleCancel(scope.$index)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="btnLoading"
          @click="handleConfirm('addForm')"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  invoicesorts_index,
  invoice_add,
  invoicesorts_getSortsAll,
  invoice_addOutTicket,
} from "@/api/financial/bill";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
export default {
  data() {
    return {
      title: "收票",
      dialogVisible: false,
      current: 1,
      size: 20,
      total: 0,
      loading: false,
      btnLoading: false,
      searchForm: {
        goods_name: "",
      },
      tableForm: {
        //表头
        addForm: {
          invoice_time: "",
          invoice_code: "",
          invoice_entity: "",
          remark: "",
        },
        //商品
        addForm_goods: [
          {
            sorts_id: "",
            goods_name: "",
            sy_num: "",
            num: "",
            unit: "",
            money: "",
            remark: "",
          },
        ],
      },
      tableData: [],
      statusList: [],
      rules: {
        invoice_time: [
          { required: true, message: "请选择日期", trigger: "change" },
        ],
        invoice_code: [
          { required: true, message: "请输入发票号码", trigger: "blur" },
        ],
        invoice_entity: [
          { required: true, message: "请输入开票单位", trigger: "blur" },
        ],
        goods_name: [
          { required: true, message: "请输入品名", trigger: "blur" },
        ],
        num: [
          { required: true, message: "请输入数量", trigger: "blur" },
          {
            pattern: /^(\d+\.?)?\d{0,2}$/,
            message: "请输入整数和两位小数",
            trigger: "blur",
          },
        ],
        sy_num: [
          { required: true, message: "请输入数量", trigger: "blur" },
          {
            pattern: /^(\d+\.?)?\d{0,2}$/,
            message: "请输入整数和两位小数",
            trigger: "blur",
          },
        ],
        unit: [
          { required: true, message: "请输入单价", trigger: "blur" },
          {
            pattern: /^(\d+\.?)?\d{0,2}$/,
            message: "请输入整数和两位小数",
            trigger: "blur",
          },
        ],
        money: [
          { required: true, message: "请输入金额", trigger: "blur" },
          {
            pattern: /^(\d+\.?)?\d{0,2}$/,
            message: "请输入整数和两位小数",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    tableForm: {
      handler(newName, oldName) {
        newName.addForm_goods.forEach((v) => {
          if (
            parseFloat(v.num) >= parseFloat(v.sy_num) &&
            this.title == "出票"
          ) {
            v.num = parseFloat(v.sy_num);
          }
        });
        let arr = [];
        newName.addForm_goods.forEach((i) => {
          if (i.goods_name.trim()) {
            arr.push(i.goods_name.trim());
          }
        });
        if (arr.length == this.tableForm.addForm_goods.length) {
          this.tableForm.addForm_goods.push({
            sorts_id: "",
            goods_name: "",
            sy_num: "",
            num: "",
            unit: "",
            money: "",
            remark: "",
            delete: true,
          });
        }
        this.tableForm.addForm_goods.forEach((v, i) => {
          if (this.tableForm.addForm_goods.length >= 1) {
            if (i !== this.tableForm.addForm_goods.length - 1) {
              v.delete = true;
            }
            if (i == this.tableForm.addForm_goods.length - 1) {
              v.delete = false;
            }
          }
        });
      },
      deep: true,
    },
  },
  created() {
    this.getData();
  },
  methods: {
    //列表数据
    getData() {
      this.loading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          page: this.current,
          per_page: this.size,
        },
        this.searchForm
      );
      invoicesorts_index(data).then((res) => {
        this.loading = false;
        if (!res.errcode) {
          this.total = res.data.list.total;
          this.tableData = res.data.list.data;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //历史单据
    tohistory() {
      this.$router.push({
        name: "financial_history",
      });
    },
    handleGenerate(item) {
      console.log(item);
      this.title = "出票";
      this.dialogVisible = true;
      this.tableForm.addForm_goods[0].goods_name = item.goods_name;
      this.tableForm.addForm_goods[0].sy_num = item.num;
      this.tableForm.addForm_goods[0].sorts_id = item.id;
    },
    // 收票 出票 删除
    handleCancel(index) {
      this.tableForm.addForm_goods.splice(index, 1);
    },
    // 收票保存
    handleConfirm(addForm) {
      this.$refs[addForm].validate((valid) => {
        if (valid) {
          if (this.title == "收票") {
            if (this.tableForm.addForm_goods.length == 1)
              throw this.$message.error("请填写商品信息");
            let arr = [...this.tableForm.addForm_goods];
            arr.forEach((v) => {
              delete v.delete;
              delete v.sorts_id;
              delete v.sy_num;
            });
            arr.splice(arr.length - 1, 1);
            let data = Object.assign(
              {
                sign: Md5(
                  objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
                ),
              },
              apiUrl().name,
              this.tableForm.addForm,
              {
                list: JSON.stringify(arr),
              }
            );
            invoice_add(data).then((res) => {
              if (!res.errcode) {
                this.dialogVisible = false;
                this.$message.success("保存成功");
                this.getData();
              } else {
                this.dialogVisible = false;
                this.$message.error(res.errmsg);
              }
            });
          } else if (this.title == "出票") {
            if (this.tableForm.addForm_goods.length == 1)
              throw this.$message.error("请填写商品信息");
            let arr = [...this.tableForm.addForm_goods];
            arr.forEach((v) => {
              delete v.delete;
              delete v.goods_name;
              delete v.sy_num;
            });
            arr.splice(arr.length - 1, 1);
            let data = Object.assign(
              {
                sign: Md5(
                  objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
                ),
              },
              apiUrl().name,
              this.tableForm.addForm,
              {
                list: JSON.stringify(arr),
              }
            );
            invoice_addOutTicket(data).then((res) => {
              if (!res.errcode) {
                this.dialogVisible = false;
                this.$message.success("保存成功");
                this.getData();
              } else {
                this.dialogVisible = false;
                this.$message.error(res.errmsg);
              }
            });
          }
        }
      });
    },
    // 关闭
    handleClose() {
      this.tableForm.addForm = {
        invoice_time: "",
        invoice_code: "",
        invoice_entity: "",
        remark: "",
      };
      this.tableForm.addForm_goods = [
        {
          sorts_id: "",
          goods_name: "",
          sy_num: "",
          num: "",
          unit: "",
          money: "",
          remark: "",
        },
      ];
    },
    //品名搜索
    querySearchAsync(queryString, cb) {
      let name = queryString.trim();
      if (name) {
        let data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
            ),
          },
          apiUrl().name,
          {
            name,
          }
        );
        invoicesorts_getSortsAll(data).then((res) => {
          let arr = [];
          res.data.list.forEach((v) => {
            arr.push({
              value: v.goods_name,
              id: v.id,
              sy_num: v.num,
            });
          });
          cb(arr);
        });
      } else {
        cb([]);
      }
    },
    handleSelect(item, index) {
      this.tableForm.addForm_goods[index].sy_num = item.sy_num;
      this.tableForm.addForm_goods[index].sorts_id = item.id;
    },
    //分页
    changeSize(e) {
      this.size = e;
      this.getData();
    },
    //分页
    changePage(e) {
      this.current = e;
      this.getData();
    },
    //重置
    reset() {
      this.$refs.searchForm.resetFields();
      this.getData();
    },
  },
};
</script>

<style scoped lang='scss'>
.el-form-item {
  margin-bottom: 10px;
}
/deep/.el-input__inner::-webkit-inner-spin-button,
/deep/.el-input__inner::-webkit-outer-spin-button {
  -webkit-appearance: none;
}
.status0 {
  color: #eb0a0a;
}
.status1 {
  color: #e6a23c;
}
.status2 {
  color: #03a98e;
}
.status3 {
  color: #999;
}
.main_tile_l {
  line-height: 42px;
  color: #181818;
  font-size: 14px;
  font-weight: 700;
  em {
    display: inline-block;
    vertical-align: 2px;
    border-radius: 1000px;
    margin-right: 5px;
    width: 6px;
    height: 6px;
    background: #03a98e;
  }
}
.addForm_flex {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}
.table_scroll {
  height: 270px;
  overflow-y: auto;
}
/deep/.table_guanli .el-table--small td .cell {
  height: 32px !important;
}
/deep/.table_guanli .el-table__body .el-form-item__content {
  margin-left: 0 !important;
}
</style>